<template>
  <!-- 编辑弹窗 -->
  <a-modal
    title="双优化分类管理"
    :visible="visible"
    :width="1010"
    :mask-closable="false"
    @cancel="handleCancel"
  >
    <a-form-model
      ref="EditFrom"
      :model="objFrom"
      :rules="rules"
      :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
      :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
    >
      <a-row :gutter="24">
        <a-col
          :md="12"
          :sm="12"
        >
          <a-form-model-item
            label="双优化名称"
            prop="name"

          >
            <BaseInput v-model="objFrom.name"  :disabled="view" />
          </a-form-model-item>
        </a-col>
        <a-col
          :md="12"
          :sm="12"
        >
          <a-form-model-item
            label="计划实施时间"
            prop="startTime"
          >
            <a-date-picker
                    :disabled="view"
              v-model="objFrom.startTime"
              style="width: 100%"
              @change="PlanningTime"
            />
          </a-form-model-item>
        </a-col>
        <a-col
          :md="12"
          :sm="12"
        >
          <a-form-model-item
            label="分类"
            prop="category"
          >
            <a-select
              v-model="objFrom.category"
              placeholder="请选择"
              @change="handleCatChanged"
              :disabled="view"
              :loading="selectLoading.loading1"
            >
              <a-select-option
                v-for="item in categoryList"
                :key="item.id"
                :value="item.id"
                :disabled="!item.state"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col
          :md="12"
          :sm="12"
        >
          <a-form-model-item
            label="详细分类"
            prop="detailedCategory"
          >
            <a-select
              v-model="objFrom.detailedCategory"
              placeholder="请选择"
              :disabled="view"
              :loading="selectLoading.loading2"
            >
              <a-select-option
                v-for="item in detailCategoryList"
                :key="item.id"
                :value="item.id"
                :disabled="!item.status"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col
                :md="12"
                :sm="12"
                v-if="objFrom.category === 111"
        >
          <a-form-model-item
                  label="设计阶段"
                  prop="designStageId"
                  class="requiredFormItem"
          >
            <a-select
                    v-model="objFrom.designStageId"
                    placeholder="请选择"
                    :disabled="view"
                    :loading="selectLoading.loading3"
            >
              <a-select-option
                      v-for="item in designPhaseList"
                      :key="item.id"
                      :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col
                :md="12"
                :sm="12"
                v-if="objFrom.category === 111"
        >
          <a-form-model-item
                  label="优化类别"
                  prop="optimizeStageId"
                  class="requiredFormItem"
          >
            <a-select
                    v-model="objFrom.optimizeStageId"
                    placeholder="请选择"
                    :disabled="view"
                    :loading="selectLoading.loading4"
            >
              <a-select-option
                      v-for="item in optimizationCategoryList"
                      :key="item.id"
                      :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col
                :md="12"
                :sm="12"
        >
          <a-form-model-item
                  label="工程类别"
                  prop="projectTypeId"
          >
            <a-select
                    v-model="objFrom.projectTypeId"
                    placeholder="请选择"
                    @change="handleProjectType"
                    :disabled="view || qualityTypes.length === 1"
                    :loading="selectLoading.loading5"
            >
              <a-select-option
                      v-for="item in qualityTypes"
                      :key="item.projectTypeId"
                      :value="item.projectTypeId"
              >
                {{ item.projectTypeName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col
                :md="12"
                :sm="12"
        >
          <a-form-model-item
                  label="分部"
                  prop="partId"
          >
            <a-select
                    v-model="objFrom.partId"
                    placeholder="请选择"
                    :disabled="view"
                    :loading="selectLoading.loading6"
            >
              <a-select-option
                      v-for="item in subItemList"
                      :key="item.id"
                      :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col
                :md="12"
                :sm="12"
        >
          <a-form-model-item
                  label="创新"
                  prop="isNew"
          >
            <a-radio-group v-model="objFrom.isNew"  :disabled="view">
              <a-radio  :value="1">是</a-radio>
              <a-radio  :value="0">否</a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col
                :md="12"
                :sm="12"
        >
          <a-form-model-item
                  label="提出人"
                  prop="proposerId"
          >
<!--            <OrgStaffAsync-->
<!--                    ref="orgStaffAsync"-->
<!--                    v-model="objFrom.proposerId"-->
<!--                    placeholder="请选择/多选"-->
<!--                    :is-lazy-load="false"-->
<!--                    :query-api="getDesignEmployee"-->
<!--                    :selected-value.sync="objFrom.proposerId"-->
<!--            />-->
            <SelectPersonByProject
                    v-model="objFrom.proposerId"
                    placeholder="请输入姓名进行查询/多选"
                    show-search
                    mode="multiple"
                    :disabled="view"
                    :row="model"
                    orgId="53085e2c9f1f4685801ef31994f57c49"
            ></SelectPersonByProject>
          </a-form-model-item>
        </a-col>
        <a-col
          :md="12"
          :sm="12"
        >
          <a-form-model-item
            label="拟实施人"
            prop="implementId"
          >
            <SelectPersonByProject
                    v-model="objFrom.implementId"
                    placeholder="请输入姓名进行查询/多选"
                    show-search
                    mode="multiple"
                    :disabled="view"
                    orgId="53085e2c9f1f4685801ef31994f57c49"
                    :row="model"
            ></SelectPersonByProject>
<!--            <OrgStaffAsync-->
<!--              ref="orgStaffAsync1"-->
<!--              v-model="objFrom.implementId"-->
<!--              placeholder="请选择/多选"-->
<!--              :is-lazy-load="false"-->
<!--              :query-api="getDesignEmployee"-->
<!--              :selected-value.sync="objFrom.implementId"-->
<!--            />-->
          </a-form-model-item>
        </a-col>

        <a-col
          :md="12"
          :sm="12"
        >
          <a-form-model-item
            label="策划效益(万)"
            prop="benefit"
          >
<!--            <BaseInput v-model="objFrom.benefit"  :disabled="view" />-->
            <a-input-number style="width: 100%" :max="9999999999" :min="0" :precision="2" placeholder="请输入" autocomplete="off"
                            v-model="objFrom.benefit"
                            :disabled="view"
                          ></a-input-number>
          </a-form-model-item>
        </a-col>
        <a-col
          :md="12"
          :sm="12"
        >
          <a-form-model-item
            label="专业类别"
            prop="professionalType"
          >
            <a-select v-model="objFrom.professionalType"  :disabled="view" placeholder="请选择">
              <a-select-option value="CIVIL">
                建筑
              </a-select-option>
              <a-select-option value="ELECTRICAL">
                机电
              </a-select-option>
              <a-select-option value="STRUCTURE">
                结构
              </a-select-option>
              <a-select-option value="LANDSCAPE">
                市政景观
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col
          :md="24"
          :sm="24"
        >
          <a-form-model-item
            label="内容概述"
            prop="content"
          >
            <BaseTextarea
              v-model="objFrom.content"
              :disabled="view"
              :rows="4"
              :max-length="3000"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <div slot="footer">
      <a-button @click="handleCancel">{{view ? '关闭': '取消'}}</a-button>
      <a-button type="primary" @click="submit" v-if="!view" :loading="loading">确定</a-button>
    </div>
  </a-modal>
</template>

<script>
import { categoryList } from '@/api/technical/optimizationPlan'
import { getProjectIdFromOrg } from '@/api/commons'
import { getProjectTypes, getProjectTypesFindIds } from '@/api/project/projects'
import { subItem } from '@/api/quality/currency' // api
import { list } from '@/api/technical/config'
import SelectPersonByProject from './selectPerson' // 人员选择
export default {
  name: 'a' + Date.now(),
  components: {
    SelectPersonByProject
  },
  props: {
    visible: {
      type: Boolean,
      required: false
    },
    model: {
      type: Object,
      default: () => null
    },
    deptId: {
      type: String,
      default: ''
    },
    view: {
      type: Boolean,
      default: false
    },
    projectInfo: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    model: {
      immediate: true,
      handler(val) {
        this.objFrom = { ...this.objFrom, ...val }
        // this.objFrom.projectTypeId= '930289049074278400'
        if(this.objFrom.projectTypeId) {
          getProjectTypesFindIds([this.objFrom.projectTypeId]).then(res=>{
          const obj = res.data.find(item=>item.sourceId === this.objFrom.projectTypeId || item.projectTypeId === this.objFrom.projectTypeId)
            if(obj) {
              this.objFrom.projectTypeId = obj.sourceId || obj.projectTypeId
              this.subItem(obj.sourceId || obj.projectTypeId)
            }

          })

        }
      }
    },
    projectInfo: {
      immediate: true,
      deep: true,
      handler(val) {
        if(val.qualityName) {
          getProjectTypesFindIds(val.qualityIds).then(res=>{
            const ids = []
            res.data.forEach(item=>{
              if(item.sourceId&&!ids.includes(item.sourceId)) {
                ids.push(item.sourceId)
              } else {
                if(!ids.includes(item.projectTypeId)) {
                  ids.push(item.projectTypeId)
                }
              }
            })
            this.getProjectTypes(ids)
          })

        }
      }
    },
    deptId: {
      immediate: true,
      handler() {
        this.$refs.orgStaffAsync && this.$refs.orgStaffAsync.getOrgsTree()
        this.$refs.orgStaffAsync1 && this.$refs.orgStaffAsync1.getOrgsTree()
      }
    }
  },
  computed: {
    detailCategoryList() {
      const index = this.categoryList.findIndex((item) => item.id === this.objFrom.category)
      return (this.categoryList[index] && this.categoryList[index].children) || []
    }
  },
  data() {
    const validateNum = (rule, value, callback) => {
      if (Number.isFinite(Number(value))) {
        callback()
      } else {
        callback(new Error('请输入正确的数字'))
      }
    }
    return {
      selectLoading: {
        loading1: false,
        loading2: false,
        loading3: false,
        loading4: false,
        loading5: false,
        loading6: false
      },
      loading: false,
      categoryList: [],
      qualityTypes: [],
      subItemList: [],
      designPhaseList: [], // 设计阶段
      optimizationCategoryList: [], //优化类别
      objFrom: {
        partId: void 0,
        optimizeStageId: void 0,
        designStageId: void 0,
        category: void 0,
        detailedCategory: void 0,
        professionalType: void 0,
        projectTypeId: void 0,
        isNew: void 0,
        proposerId: [],
        implementId: [],
        startTime: void 0,
      },
      state: [
        { name: '完成', value: 1 },
        { name: '未完成', value: 0 },
        { name: '成都分公司', value: 2 }
      ],
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择时间', trigger: 'change' }],
        detailedCategory: [{ required: true, message: '请选择详细分类', trigger: 'change' }],
        designStageId: [{ required: true, message: '请选择设计阶段', trigger: 'change' }],
        optimizeStageId: [{ required: true, message: '请选择优化类别', trigger: 'change' }],
        category: [{ required: true, message: '请选择分类', trigger: 'change' }],
        projectTypeId: [{ required: true, message: '请选择工程类别', trigger: 'change' }],
        partId: [{ required: true, message: '请选择分部', trigger: 'change' }],
        implementId: [{ required: true, message: '请选择拟实施人', trigger: 'change' }],
        proposerId: [{ required: true, message: '请选择提出人', trigger: 'change' }],
        professionalType: [{ required: true, message: '请选择专业类别', trigger: 'change' }],
        isNew: [{ required: true, message: '请选择是否创新', trigger: 'change' }],
        benefit: [
          { required: true, message: '请输入策划效益', trigger: 'change' },
          { validator: validateNum, trigger: 'change' }
        ],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getDicts()
    this.getCategoryList()
  },
  methods: {
    getDicts() {
      // 设计阶段下拉
      this.selectLoading.loading3 = true
      list({type: 17}).then(res=>{
        this.selectLoading.loading3 = false
         this.designPhaseList = res.data;
      })
      this.selectLoading.loading4 = true
      list({type: 18}).then(res=>{
        this.selectLoading.loading4 = false
        this.optimizationCategoryList = res.data
      })
    },
    // 获取工程类别
    getProjectTypes(qualityIds) {
      this.selectLoading.loading5 = true
      getProjectTypes().then((res) => {
        this.qualityTypes = res.data?.filter(item=> qualityIds.includes(item.projectTypeId))
        this.selectLoading.loading5 = false
        if(!this.model.projectTypeId &&  this.qualityTypes.length === 1) {
          this.objFrom.projectTypeId = this.qualityTypes[0].projectTypeId
          this.subItem(this.objFrom.projectTypeId)
        }
      })
    },
    // 分部分项
    subItem(id) {
      const data = {
        id,
        enabled: true,
        sources: 0
      }
      this.selectLoading.loading6 = true
      subItem.getList(data).then(res => {
        this.selectLoading.loading6 = false
        this.subItemList = res?.data[0]?.children[0]?.children
      })
    },
    handleProjectType(val) {
      this.objFrom.partId = void 0
      this.subItemList = []
      this.subItem(val)
    },
    async getDesignEmployee() {
      try {
        const p1 = await getProjectIdFromOrg({
          pid: this.deptId,
          parentCodes: ['designManage'],
          pageNum: 1,
          pageSize: 100
        })
        const p2 = getProjectIdFromOrg({
          pid: 'ecf764c08dd94fa889ce31c380b1241c',
          code: 'BCDDM',
          pageNum: 1,
          pageSize: 1000
        })
        const p3 = getProjectIdFromOrg({
          pid: 'cdcfa929b51a47269f336364860c9f0c',
          code: 'BCDDM',
          pageNum: 1,
          pageSize: 1000
        })
        const p4 = getProjectIdFromOrg({
          pid: '53085e2c9f1f4685801ef31994f57c49',
          code: 'designManage',
          pageNum: 1,
          pageSize: 1000
        })
        return Promise.all([p1, p2, p3, p4]).then(([res1, res2, res3, res4]) => {
          const list = (res1?.data?.list || []).concat(res2?.data?.list || []).concat(res3?.data?.list || []).concat(res4?.data?.list || [])
          return {
            status: 200,
            data: list
          }
        })
      } catch (e) {
        return Promise.reject(e)
      }
    },
    handleCatChanged(val) {
      this.objFrom.optimizeStageId = void 0
      this.objFrom.designStageId = void 0
      this.objFrom.detailedCategory = void 0
      let o = this.categoryList.find(item=> item.id === val)
      this.objFrom.categoryName = o?.name
    },
    handleCancel() {
      this.$refs.EditFrom.resetFields()
      this.$emit('cancel')
    },
    getCategoryList() {
      this.selectLoading.loading1 = true
      categoryList().then((res) => {
        this.selectLoading.loading1 = false
        this.categoryList = res.data || []
      })
    },
    submit() {
      this.$refs.EditFrom.validate((valid) => {
        if (valid) {
          this.loading = true
          const projectTypeObj = this.qualityTypes.find(item=> item.projectTypeId === this.objFrom.projectTypeId)
          const partObj = this.subItemList.find(item=> item.id === this.objFrom.partId)
          const optimizeStageObj = this.optimizationCategoryList.find(item=> item.id === this.objFrom.optimizeStageId)
          const designStageObj = this.designPhaseList.find(item=> item.id === this.objFrom.designStageId)
          const data = {
            ...this.objFrom,
            projectType: projectTypeObj?.projectTypeName,
            part: partObj?.name,
            optimizeStage: optimizeStageObj,
            designStage: designStageObj
          }
          if(!designStageObj) {
            delete data.designStage
          }
          if(!optimizeStageObj) {
            delete data.optimizeStage
          }
          if(data.id) {
              delete data.designStageName
              delete data.optimizeStageName
              delete data.doubleOptimizationBasicVO
              delete data.detailedCategoryName
              delete data.optimizeStageId
              delete data.designStageId
          }


          console.log(data, "objFrom")
          this.$emit('ok', data)
          setTimeout(()=>{
            this.loading = false
          }, 1000)
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    //计划实施时间
    PlanningTime(date, datestring) {
      this.objFrom.startTime = datestring
    }
  }
}
</script>

<style scoped lang="less">
  /deep/ .requiredFormItem.ant-input-number {
    border: 0!important;
  }
  /deep/ .ant-input-number:focus {
    box-shadow: none!important;
  }
 /deep/ .ant-input-number-handler-wrap {
    display: none!important;
  }
</style>